package com.wn.main.ui.home.view

import android.Manifest
import android.annotation.SuppressLint
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.tbruyelle.rxpermissions3.RxPermissions
import com.wn.common.constant.KEY_VIDEO_PLAY_LIST
import com.wn.common.constant.VIDEO_ACTIVITY_PLAYER
import com.wn.common.db.entity.VideoInfo
import com.wn.framework.base.BaseFragment
import com.wn.framework.decoration.StaggeredItemDecoration
import com.wn.main.R
import com.wn.main.databinding.FragmentHomeVideoBinding
import com.wn.main.ui.home.adapter.HomeVideoItemAdapter
import com.wn.main.ui.home.viewmodel.HomeViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @Author: wn
 * @Date: 2024/10/28 17:06
 * @Description: 首页视频列表
 */
@AndroidEntryPoint
class HomeVideoFragment : BaseFragment<FragmentHomeVideoBinding>() {

  override fun getLayoutRes() = R.layout.fragment_home_video

  private val viewModel by viewModels<HomeViewModel>()

  @Inject
  lateinit var adapter: HomeVideoItemAdapter

  @Inject
  lateinit var itemDecoration: StaggeredItemDecoration

  @SuppressLint("CheckResult")
  override fun initView() {
    super.initView()
    val spanCount = 2
    val manager = StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL)
    mBinding.apply {
      /**
       * 关闭下拉刷新 上拉加载
       */
      refreshLayout.setEnableRefresh(false)
      refreshLayout.setEnableLoadMore(false)

      recyclerView.layoutManager = manager
      recyclerView.addItemDecoration(itemDecoration)
      recyclerView.adapter = adapter
    }

    // 点击事件 权限认证 需要传递 fragment 或者 activity 因此这里使用 lambda 触发
    adapter.onItemClickListener = { _, _ ->
      RxPermissions(this).request(
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE
      ).subscribe {
        if (it)
          ARouter.getInstance()
            .build(VIDEO_ACTIVITY_PLAYER)
            .withParcelableArrayList(
              KEY_VIDEO_PLAY_LIST,
              adapter.getData() as ArrayList<VideoInfo>
            )
            .navigation()
        else
          ToastUtils.showLong(com.wn.framework.R.string.default_agree_permission)
      }
    }
  }

  private lateinit var job: Job
  override fun initData() {
    super.initData()
    if (::job.isInitialized) job.cancel()
    job = lifecycleScope.launch {
      lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
        // 获取 首页视频列表 -- 此处是从 本地assets目录下读取的 json文件 转为 MutableList<VideoInfo>
        launch {
          viewModel.getVideoList().collect {
            mBinding.viewEmptyData.isVisible = it.isNullOrEmpty()
            this@HomeVideoFragment.adapter.setData(it)
          }
        }
        // 加载 loading 和 停止刷新
        launch {
          // delay(20) // 确保 loading 先为 true-->控制 刷新
          viewModel.loading.collect {
            if (it) showLoading() else dismissLoading()
          }
        }
      }
    }
  }

  /**
   * Home键或者锁屏 后 数据重复请求
   */
  override fun onStop() {
    super.onStop()
    if (::job.isInitialized) job.cancel()
  }
}